package com.huonan.utils;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;

public class ThreadPoolUtils {
    public static void main(String[] args) {

        //阻塞因子
        double blockingCoefficient = 0.2;
        // 最佳的线程数 = CPU可用核心数 / (1 - 阻塞系数)
        int poolSize = (int) (RuntimeUtil.getProcessorCount() / (1 - blockingCoefficient));
        // 创建线程池
        ExecutorService executor = ThreadUtil.newExecutor(
                5,
                poolSize,
                60
        );

        // 提交任务
        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                String threadName = Thread.currentThread().getName();
                long sleepTime = RandomUtil.randomLong(1000, 5000);
                System.out.println(StrUtil.format("{}: Start. Sleep {}ms", threadName, sleepTime));
                ThreadUtil.sleep(sleepTime);
                System.out.println(StrUtil.format("{}: End.", threadName));
            });
        }

        // 关闭线程池
        executor.shutdown();
    }


        public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
            //阻塞因子
            double blockingCoefficient = 0.2;
            // 最佳的线程数 = CPU可用核心数 / (1 - 阻塞系数)
            int poolSize = (int) (RuntimeUtil.getProcessorCount() / (1 - blockingCoefficient));
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10); // 核心线程数
            executor.setMaxPoolSize(poolSize); // 最大线程数
            executor.setQueueCapacity(100); // 任务队列容量
            executor.setThreadNamePrefix("MyThreadPool-"); // 线程名称前缀
            executor.initialize();
            return executor;
    }
}
